package com.muchenx.util;

import org.apache.commons.lang3.StringUtils;

import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

public final class Assert {

    public static void state(boolean isTrue, String error) {
        if (!isTrue) {
            UIComponentUtil.errorAlert(error);
            interrupt(error);
        }
    }

    public static void notNull(Object value, String error) {
        if (isNull(value)) {
            UIComponentUtil.errorAlert(error);
            interrupt(error);
        }
    }

    public static void notNull(Object value, String error, Consumer<Object> then) {
        if (isNull(value)) {
            UIComponentUtil.errorAlert(error);
            interrupt(error);
        }
        then.accept(value);
    }

    public static <T, R> R notNull(T value, String error, Function<T, R> then) {
        if (isNull(value)) {
            UIComponentUtil.errorAlert(error);
            interrupt(error);
        }
        return then.apply(value);
    }

    private static boolean isNull(Object value) {
        return value == null || (value instanceof CharSequence && StringUtils.isEmpty((CharSequence) value));
    }

    private static void interrupt(String error) {
        throw new IllegalArgumentException(error);
    }
}
